<template>
  <div class="history-container">
    <h2>历史记录</h2>
    <el-tabs v-model="activeTab" class="history-tabs" @tab-change="onTabChange">
      <el-tab-pane label="数据检索" name="retrieve" />
      <el-tab-pane label="LLM模型对话" name="llm" />
    </el-tabs>
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-else-if="filteredList.length === 0" class="empty">
      <el-empty :description="activeTab === 'retrieve' ? '暂无数据检索历史' : '暂无LLM模型对话历史'" />
    </div>
    <div v-else class="list">
      <el-card v-for="item in filteredList" :key="item.id" class="item" @click="open(item)">
        <div class="row">
          <el-tag :type="item.type === 'retrieve' ? 'success' : 'info'" size="small">
            {{ item.type === 'retrieve' ? '检索' : 'LLM对话' }}
          </el-tag>
          <span class="time">{{ formatTime(item.timestamp) }}</span>
        </div>
        <div class="summary">{{ displaySummary(item) }}</div>
        <el-button type="danger" :icon="Delete" circle class="delete-btn" @click.stop="deleteRecord(item.id)"></el-button>
      </el-card>
    </div>
    <div class="ops">
      <el-button type="danger" @click="clearAll" plain>清空历史</el-button>
    </div>
  </div>
  <div class="back-btn">
    <back-button></back-button>
  </div>
</template>

<script setup name="UserHistory">
import { computed, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { Delete, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { llmHistory, searchHistory } from '@/api'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

const store = useStore()
const router = useRouter()
const route = useRoute()

// 从数据库获取的历史记录列表
const llmHistoryList = ref([])
const searchHistoryList = ref([])
const loading = ref(false)

// 选项卡状态：retrieve | llm
const TAB_KEY = 'aa_history_active_tab'
const activeTab = ref('retrieve')

// 根据当前选项卡显示对应的历史记录列表
const filteredList = computed(() => {
  if (activeTab.value === 'llm') {
    return llmHistoryList.value.map(item => ({
      id: item.id,
      type: 'llm',
      routeName: 'LLMProcess',
      timestamp: item.timestamp,
      summary: `LLM: ${(item.prompt || '').slice(0, 20)}${(item.prompt || '').length > 20 ? '…' : ''}`,
      data: item
    }))
  } else {
    return searchHistoryList.value.map(item => ({
      id: item.id,
      type: 'retrieve',
      routeName: 'TextRetrieve',
      timestamp: item.timestamp,
      summary: `检索: "${item.keyword}"（${item.result_count}条）`,
      data: item
    }))
  }
})

const displaySummary = (item) => {
  return item.summary || '历史记录'
}


const formatTime = (ts) => {
  const d = new Date(ts)
  const yyyy = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const mi = String(d.getMinutes()).padStart(2, '0')
  const ss = String(d.getSeconds()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
}

/**
 * 打开历史记录，还原页面状态
 * @param {Object} item - 历史记录项
 */
const open = async (item) => {
  try {
    if (item.type === 'llm') {
      // 获取LLM历史记录详情
      const response = await llmHistory.detail(item.id)
      if (response.data.status === 'success') {
        const data = response.data.data
        // 将数据转换为快照格式，保存到store
        const snapshot = data.session_state || {
          form: { inputText: data.prompt },
          result: data.response,
          metadata: {
            model: data.model,
            input_length: data.input_length,
            output_length: data.output_length
          }
        }
        // 生成一个临时ID用于store
        const tempId = `llm_${item.id}_${Date.now()}`
        // 直接保存到本地store，不调用API
        store.commit('history/ADD_RECORD', {
          id: tempId,
          type: 'llm',
          routeName: 'LLMProcess',
          timestamp: data.timestamp || Date.now(),
          summary: `LLM: ${(data.prompt || '').slice(0, 20)}${(data.prompt || '').length > 20 ? '…' : ''}`,
          snapshot
        })
        router.push({ name: 'LLMProcess', query: { historyId: tempId } })
      }
    } else {
      // 获取检索历史记录详情
      const response = await searchHistory.detail(item.id)
      if (response.data.status === 'success') {
        const data = response.data.data
        // 将数据转换为快照格式，保存到store
        // 优先使用page_state，如果存在但缺少关键字段，则合并补充
        let snapshot = data.page_state || {}
        
        // 确保快照包含完整的表单信息
        if (!snapshot.form) {
          snapshot.form = {
            keyword: data.keyword || '',
            searchType: data.search_type || 'simple',
            lang1: data.lang1 || '',
            lang2: data.lang2 || '',
            threshold: data.threshold || 0.1
          }
        } else {
          // 如果form存在但字段不完整，补充缺失的字段
          snapshot.form = {
            keyword: snapshot.form.keyword || data.keyword || '',
            searchType: snapshot.form.searchType || data.search_type || 'simple',
            lang1: snapshot.form.lang1 || data.lang1 || '',
            lang2: snapshot.form.lang2 || data.lang2 || '',
            threshold: typeof snapshot.form.threshold === 'number' ? snapshot.form.threshold : (data.threshold || 0.1)
          }
        }
        
        // 确保results字段存在（即使为空数组，也要确保字段存在）
        if (!Array.isArray(snapshot.results)) {
          snapshot.results = []
        }
        
        // 确保pagination字段存在且完整
        if (!snapshot.pagination) {
          snapshot.pagination = {
            currentPage: 1,
            pageSize: 10,
            totalResults: data.result_count || 0,
            totalPages: Math.ceil((data.result_count || 0) / 10)
          }
        } else {
          // 补充缺失的分页字段
          snapshot.pagination = {
            currentPage: snapshot.pagination.currentPage || 1,
            pageSize: snapshot.pagination.pageSize || 10,
            totalResults: snapshot.pagination.totalResults || data.result_count || 0,
            totalPages: snapshot.pagination.totalPages || Math.ceil((data.result_count || 0) / 10)
          }
        }
        
        // 确保hasSearched字段存在
        if (typeof snapshot.hasSearched !== 'boolean') {
          snapshot.hasSearched = true
        }
        
        // 生成一个临时ID用于store
        const tempId = `search_${item.id}_${Date.now()}`
        // 直接保存到本地store，不调用API
        store.commit('history/ADD_RECORD', {
          id: tempId,
          type: 'retrieve',
          routeName: 'TextRetrieve',
          timestamp: data.timestamp || Date.now(),
          summary: `检索: "${data.keyword}"（${data.result_count || 0}条）`,
          snapshot
        })
        router.push({ name: 'TextRetrieve', query: { historyId: tempId } })
      }
    }
  } catch (error) {
    console.error('加载历史记录详情失败:', error)
    ElMessage.error('加载历史记录失败')
  }
}

/**
 * 清空所有历史记录
 */
const clearAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清空所有${activeTab.value === 'llm' ? 'LLM对话' : '数据检索'}历史记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    if (activeTab.value === 'llm') {
      // 批量删除LLM历史记录
      const deletePromises = llmHistoryList.value.map(item => 
        llmHistory.remove(item.id).catch(() => {}) // 忽略单个删除失败
      )
      await Promise.all(deletePromises)
      llmHistoryList.value = []
    } else {
      // 批量删除检索历史记录
      const deletePromises = searchHistoryList.value.map(item => 
        searchHistory.remove(item.id).catch(() => {}) // 忽略单个删除失败
      )
      await Promise.all(deletePromises)
      searchHistoryList.value = []
    }
    ElMessage.success('清空成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空历史记录失败:', error)
      ElMessage.error('清空失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 删除单条历史记录
 * @param {number} id - 历史记录ID
 */
const deleteRecord = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条历史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (activeTab.value === 'llm') {
      await llmHistory.remove(id)
      llmHistoryList.value = llmHistoryList.value.filter(item => item.id !== id)
    } else {
      await searchHistory.remove(id)
      searchHistoryList.value = searchHistoryList.value.filter(item => item.id !== id)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除历史记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 从数据库获取历史记录列表
 */
const fetchHistoryList = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    // 未登录，清空列表
    llmHistoryList.value = []
    searchHistoryList.value = []
    return
  }
  
  loading.value = true
  try {
    // 并行获取两种历史记录
    const [llmRes, searchRes] = await Promise.all([
      llmHistory.list({ limit: 100 }).catch(() => ({ data: { status: 'success', data: { items: [] } } })),
      searchHistory.list({ limit: 100 }).catch(() => ({ data: { status: 'success', data: { items: [] } } }))
    ])
    
    if (llmRes.data.status === 'success') {
      llmHistoryList.value = llmRes.data.data.items || []
    }
    if (searchRes.data.status === 'success') {
      searchHistoryList.value = searchRes.data.data.items || []
    }
  } catch (error) {
    console.error('获取历史记录列表失败:', error)
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 从数据库获取历史记录
  fetchHistoryList()

  // 优先读 URL，其次 localStorage
  const qTab = route.query.tab
  if (qTab === 'retrieve' || qTab === 'llm') {
    activeTab.value = qTab
    try { localStorage.setItem(TAB_KEY, activeTab.value) } catch (e) { /* ignore */ }
  } else {
    try {
      const saved = localStorage.getItem(TAB_KEY)
      if (saved === 'retrieve' || saved === 'llm') {
        activeTab.value = saved
      }
    } catch (e) { /* ignore */ }
  }
})

// 监听选项卡切换，重新获取数据
const onTabChange = () => {
  try {
    localStorage.setItem(TAB_KEY, activeTab.value)
  } catch (e) { /* ignore */ }
  // 将 tab 同步到 URL，刷新可保持
  router.replace({ name: 'History', query: { ...route.query, tab: activeTab.value } })
  // 重新获取数据
  fetchHistoryList()
}
</script>

<style scoped>
.history-container {
  padding: 20px;
}
.history-tabs {
  margin-top: 12px;
}
.list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-top: 12px;
}
.item {
  cursor: pointer;
}
.row {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 8px;
}
.time {
  color: #909399;
  font-size: 12px;
}
.summary {
  color: #303133;
}
.ops {
  margin-top: 20px;
}
.empty {
  margin-top: 40px;
}

/* 响应式：缩窄屏时单列展示，tabs 自适应换行 */
@media (max-width: 768px) {
  .list {
    grid-template-columns: 1fr;
  }
}
</style>
